package com.example.a001.yyue;

import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

import com.example.a001.R;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class SongDetailActivity extends AppCompatActivity {
    private MediaPlayer mediaPlayer;
    private List<MusicData> musicList;
    private int currentPosition;
    private ImageView btnPlay, btnPrev, btnNext, btnPlayMode;
    private ImageView btnBack;
    private boolean isRandomPlay = false;
    private SeekBar seekBar;
    private TextView tvCurrentTime, tvTotalTime;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_song_detail);

        // 获取传递的数据
        musicList = getIntent().getParcelableArrayListExtra("MUSIC_LIST");
        currentPosition = getIntent().getIntExtra("CURRENT_POSITION", 0);

        initViews();
        updateSongInfo();
        initMediaPlayer();
    }

    private void initViews() {
        btnPlay = findViewById(R.id.btnDetailPlay);
        btnPrev = findViewById(R.id.btnDetailPrev);
        btnNext = findViewById(R.id.btnDetailNext);
        btnPlayMode = findViewById(R.id.btnPlayMode);
        btnBack = findViewById(R.id.btnBack);
        seekBar = findViewById(R.id.seekBar);
        tvCurrentTime = findViewById(R.id.tvCurrentTime);
        tvTotalTime = findViewById(R.id.tvTotalTime);

        btnPlay.setOnClickListener(v -> togglePlay());
        btnPrev.setOnClickListener(v -> playPrevious());
        btnNext.setOnClickListener(v -> playNext());
        btnPlayMode.setOnClickListener(v -> togglePlayMode());
        btnBack.setOnClickListener(v -> onBackPressed());

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    mediaPlayer.seekTo(progress);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 暂停更新进度条
                handler.removeCallbacks(updateSeekBarRunnable);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 恢复更新进度条
                handler.postDelayed(updateSeekBarRunnable, 100);
            }
        });
    }

    private void updateSongInfo() {
        MusicData currentMusic = musicList.get(currentPosition);
        ((TextView) findViewById(R.id.tvTitle)).setText(currentMusic.getTitle());
        ((TextView) findViewById(R.id.tvArtist)).setText(currentMusic.getArtist());
    }

    private void initMediaPlayer() {
        mediaPlayer = new MediaPlayer();
        try {
            mediaPlayer.setDataSource(musicList.get(currentPosition).getPath());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(mp -> {
                seekBar.setMax(mediaPlayer.getDuration());
                tvTotalTime.setText(formatTime(mediaPlayer.getDuration()));
                startSeekBarUpdate();
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void togglePlay() {
        if (mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            btnPlay.setImageResource(R.drawable.ic_play_btn_play);
            handler.removeCallbacks(updateSeekBarRunnable);
        } else {
            mediaPlayer.start();
            btnPlay.setImageResource(R.drawable.ic_play_btn_pause);
            startSeekBarUpdate();
        }
    }

    private void playPrevious() {
        if (isRandomPlay) {
            currentPosition = new Random().nextInt(musicList.size());
        } else {
            if (currentPosition > 0) {
                // 当前不是第一首歌曲，正常播放上一首
                currentPosition--;
            } else {
                // 当前是第一首歌曲，跳转到最后一首
                currentPosition = musicList.size() - 1;
            }
        }
        switchMusic();
    }

    private void playNext() {
        if (isRandomPlay) {
            currentPosition = new Random().nextInt(musicList.size());
        } else {
            if (currentPosition < musicList.size() - 1) {
                currentPosition++;
            } else {
                // 如果是最后一首歌曲，跳转到第一首
                currentPosition = 0;
            }
        }
        switchMusic();
    }

    private void switchMusic() {
        mediaPlayer.reset();
        try {
            mediaPlayer.setDataSource(musicList.get(currentPosition).getPath());
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(mp -> {
                seekBar.setMax(mediaPlayer.getDuration());
                tvTotalTime.setText(formatTime(mediaPlayer.getDuration()));
                startSeekBarUpdate();
            });
            updateSongInfo();
            btnPlay.setImageResource(R.drawable.ic_play_btn_play); // 切换到新歌曲时重置按钮状态
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void togglePlayMode() {
        isRandomPlay = !isRandomPlay;
        if (isRandomPlay) {
            btnPlayMode.setImageResource(R.drawable.ic_play_btn_shuffle);
        } else {
            btnPlayMode.setImageResource(R.drawable.ic_play_btn_loop);
        }
    }

    private void startSeekBarUpdate() {
        handler.postDelayed(updateSeekBarRunnable, 100);
    }

    private Runnable updateSeekBarRunnable = new Runnable() {
        @Override
        public void run() {
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                int currentPosition = mediaPlayer.getCurrentPosition();
                seekBar.setProgress(currentPosition);
                tvCurrentTime.setText(formatTime(currentPosition));
            }
            handler.postDelayed(this, 100);
        }
    };

    private String formatTime(int time) {
        int minutes = time / 1000 / 60;
        int seconds = time / 1000 % 60;
        return String.format("%d:%02d", minutes, seconds);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
        handler.removeCallbacks(updateSeekBarRunnable);
    }
}